package com.example.forum.exception;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {       //全局异常处理

    @ResponseBody
    @ExceptionHandler(ApplicationException.class)
    public AppResult handleApplicationException(ApplicationException e){
        //打印异常
        e.printStackTrace();
        log.error(e.getMessage());

        if(e.getErrorResult()!=null){
            return e.getErrorResult();
        }
        return AppResult.failed(e.getMessage());
    }

    //处理未捕获的其他异常

    @ResponseBody
    @ExceptionHandler(Exception.class)
    public AppResult handleExpection(Exception e){
        //打印异常
        e.printStackTrace();
        log.error(e.getMessage());

        if(e.getMessage()==null){
            return AppResult.failed(ResultCode.ERROR_SERVICES);
        }
        //默认返回异常信息
        return AppResult.failed(e.getMessage());

    }


}
